package com.harmonyos.cases.utils;

/**
 * json5文件解析
 * 由于java不能直接解析json5文件，所以需要将json5转换为json再进行解析使用
 */
public class Json5Parser {
    public static String removeComments(String json5) {
        // 匹配单行注释和多行注释
//        return json5.replaceAll("//.*|/\\*[\\s\\S]*?\\*/", "");
        return json5.replaceAll("(?!http://|https://)^//.*|/\\\\*[\\s\\S]*?\\*/", "");
    }

    public static String replaceSingleQuotes(String json5) {
        StringBuilder result = new StringBuilder();
        boolean inSingleQuoteString = false;

        for (int i = 0; i < json5.length(); i++) {
            char currentChar = json5.charAt(i);

            if (currentChar == '\'' && !inSingleQuoteString) {
                inSingleQuoteString = true;
                result.append('"');
            } else if (currentChar == '\'' && inSingleQuoteString) {
                inSingleQuoteString = false;
                result.append('"');
            } else {
                result.append(currentChar);
            }
        }

        return result.toString();
    }

    public static String removeTrailingCommas(String json5) {
        return json5.replaceAll(",\\s*([}\\]])", "$1");
    }

    public static String addQuotesToKeys(String json5) {
        return json5.replaceAll("([\\{,]\\s*)([a-zA-Z_][a-zA-Z0-9_]*)(\\s*:\\s*)", "$1\"$2\"$3");
    }

    public static String parseJson5(String json5) {
        // 去除注释
        json5 = removeComments(json5);

        // 处理单引号字符串
        json5 = replaceSingleQuotes(json5);

        // 处理尾随逗号
        json5 = removeTrailingCommas(json5);

        // 为未加引号的键名添加引号
        json5 = addQuotesToKeys(json5);

        return json5;
    }
}
